"use client";

import { Form, Input, Modal } from "antd";
import { api } from "~/trpc/react";
import type { Step } from "@prisma/client";
import { useEffect } from "react";

interface StepFormProps {
  taskId: string;
  open: boolean;
  initialValues?: Step;
  onCancel: () => void;
  onSuccess: () => void;
}

interface StepFormValues {
  title: string;
  description?: string;
}

export function StepForm({ taskId, open, initialValues, onCancel, onSuccess }: StepFormProps) {
  const [form] = Form.useForm<StepFormValues>();

  const createMutation = api.steps.create.useMutation({
    onSuccess: () => {
      form.resetFields();
      onSuccess();
    },
  });

  const updateMutation = api.steps.update.useMutation({
    onSuccess: () => {
      onSuccess();
    },
  });

  useEffect(() => {
    if (open && initialValues) {
      form.setFieldsValue(initialValues);
    }
  }, [open, initialValues, form]);

  const handleSubmit = async (values: StepFormValues) => {
    try {
      if (initialValues) {
        await updateMutation.mutateAsync({
          stepId: initialValues.id,
          ...values,
        });
      } else {
        await createMutation.mutateAsync({
          taskId,
          ...values,
        });
      }
    } catch (error) {
      console.error("提交步骤表单时出错:", error);
    }
  };

  return (
    <Modal
      title={initialValues ? "编辑步骤" : "添加步骤"}
      open={open}
      onCancel={onCancel}
      onOk={() => form.submit()}
      confirmLoading={createMutation.isLoading || updateMutation.isLoading}
    >
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
      >
        <Form.Item
          name="title"
          label="步骤标题"
          rules={[{ required: true, message: "请输入步骤标题" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item name="description" label="步骤描述">
          <Input.TextArea rows={4} />
        </Form.Item>
      </Form>
    </Modal>
  );
} 